﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Apps.ServiceImpl.Attendance.Repositories.Interface;
using EzDesk.Apps.Model.Attendance;

namespace EzDesk.Apps.ServiceImpl.Attendance.Repositories
{
    public partial class AttendanceInfoRepository : IAttendanceInfoRepository
    {
        EzDeskAttendanceDataContext _db;

        public AttendanceInfoRepository(EzDeskAttendanceDataContext db)
        {
            this._db = db;
        }

        public Guid Add(AttendanceInfo model, bool saveChanges)
        {   
            _db.ez_AttendanceInfos.InsertOnSubmit(
                new ez_AttendanceInfo()
                {
                    AttendanceId = model.Id,
                    ActionTime = model.ActionTime,
                    Date = model.Date,
                    AttendanceType = (int)model.AttendanceType,
                    Explanation = model.Explanation,
                    IsAbnormalAttendance = model.IsAbnormalAttendance,
                    UserId = model.UserId
                });
            if (saveChanges)
            {
                this.SaveChanges();
            }
            return model.Id;
        }

        public AttendanceInfo GetById(Guid id)
        {
            throw new NotImplementedException();
        }

        public IQueryable<AttendanceInfo> GetAll()
        {
            return _db.ez_AttendanceInfos.Select(
                p => new AttendanceInfo()
                {
                    Id = p.AttendanceId,
                    Date = p.Date,
                    ActionTime = p.ActionTime,
                    UserId = p.UserId,
                    AttendanceType = (AttendanceType)p.AttendanceType,
                    Explanation = p.Explanation,
                    IsAbnormalAttendance = p.IsAbnormalAttendance,
                }
                );
        }

        public void Delete(Guid id, bool saveChanges)
        {
            throw new NotImplementedException();
        }

        public void Update(AttendanceInfo model, bool saveChanges)
        {
            var entity = _db.ez_AttendanceInfos.Where(p => p.AttendanceId == model.Id)
                .SingleOrDefault();

            entity.IsAbnormalAttendance = model.IsAbnormalAttendance;
            entity.ActionTime = model.ActionTime;
            entity.Date = model.Date;
            entity.AttendanceType = (int)model.AttendanceType;
            entity.Explanation = model.Explanation;
            entity.IsAbnormalAttendance = model.IsAbnormalAttendance;
            entity.UserId = model.UserId;
                    
            if (saveChanges)
            {
                SaveChanges();
            }
        }

        public void SaveChanges()
        {
            _db.SubmitChanges();
        }
    }
}
